import React, {useEffect, useRef, useState} from "react";
import {Button} from "antd";
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormInstance,
  ProFormList,
  ProFormMoney,
  ProFormSelect, ProFormText
} from "@ant-design/pro-form";
import {PlusOutlined} from "@ant-design/icons";

import {findByAgentBySelectList} from "@/services/ant-design-pro/agent";
import {useMount, useRequest} from "ahooks";
import {editTaocan, findByTaoCanGoodsList} from "@/services/ant-design-pro/taocan";
import {ProFormItem} from "@ant-design/pro-form/lib/components";
import MyUpload from "@/components/MyUpload";
import {ProFormTextArea} from "@ant-design/pro-components";
interface Props {
  row?:API.TaoCanMaster,
  taocanId:number | 0,
  onSuccess?: () => void;
}
const EditDialog: React.FC<Props> = (props) => {
  const {taocanId,row,onSuccess} = props
  const [agentId, setAgent] = useState<number> ( 0 );
  const formRef = useRef<ProFormInstance> ();
  // @ts-ignore
  const {
    runAsync: fetchByList,
   data: dataList,
  } = useRequest ( findByTaoCanGoodsList, {
    debounceWait: 100,
    manual: true,
  } );
  useEffect ( () => {
    fetchByList ( {taocanId: taocanId, agentId: agentId} ).then ( res => {
      let data = res.data;
      getSuanGoods(data);
      //  formRef.set("goods",data)
     // formRef.current?.setFieldValue ( "goods", data );
    } )

  }, [agentId] );
  useMount(()=>{
    if(taocanId>0){
      // @ts-ignore
      setAgent(row?.agentId)
    }
  })


  // @ts-ignore
  const getSuanGoods=(fieldValue: [API.GoodsTaoCan]=[])=> {
    if(fieldValue.length>0) {
      let paymentAmount = 0;
      let totalAmount = 0;
      let discountAmount = 0;
      let quantity = 0;
      // @ts-ignore
      let newValue: [API.GoodsTaoCan] = []
      for (let i = 0; i < fieldValue.length; i++) {
        let goodsTaoCan = fieldValue[i];
        quantity=quantity+(goodsTaoCan.quantity?goodsTaoCan.quantity:0);
        goodsTaoCan.quantity=goodsTaoCan.quantity?goodsTaoCan.quantity:0;
        goodsTaoCan.paymentAmount = (goodsTaoCan.quantity * goodsTaoCan.price)
        goodsTaoCan.totalAmount = (goodsTaoCan.quantity * goodsTaoCan.totalAmountL)
        goodsTaoCan.discountAmount = (goodsTaoCan.quantity * goodsTaoCan.discountAmountL)
        paymentAmount = paymentAmount + goodsTaoCan.paymentAmount;
        totalAmount = totalAmount + goodsTaoCan.totalAmount;
        discountAmount = discountAmount + goodsTaoCan.discountAmount;
        newValue.push ( goodsTaoCan );
      }
      if (formRef.current != undefined) {
// @ts-ignore
        formRef.current.setFieldValue ( "goods", newValue );
        formRef.current.setFieldValue ( "totalAmount", totalAmount );
        formRef.current.setFieldValue ( "paymentAmount", paymentAmount );
        formRef.current.setFieldValue ( "discountAmount", discountAmount );
        formRef.current.setFieldValue ( "quantity", quantity );
        console.log ( newValue )
      }
    }
  }

  return (
    <ModalForm<API.TaoCanMaster>
      width={1000}
      initialValues={row}
      formRef={formRef}
      title="新建表单"
      trigger={
        <Button  ghost  type="primary">
          <PlusOutlined/>
          {taocanId>0?'編輯':'添加套餐'}
        </Button>
      }
      onVisibleChange={(b)=>{
        if(b){
          setTimeout(()=>{
            setAgent(taocanId)
          },1000)

      }}}

      onValuesChange={((value) => {
        let fieldValue:[API.GoodsTaoCan] = formRef.current?.getFieldValue("goods");
      getSuanGoods(fieldValue);

    })} onFinish={(val)=>{
     return new Promise<boolean>((resolve, reject) => {
       editTaocan(val).then(res=>{
         if (onSuccess) {
           onSuccess ()
         }
         resolve(true)
       }).catch(e=>{
         reject(false)
       })
     })
    }} >
      <ProFormText
        width="sm"
        name="id"
        hidden={true}
        label="Id"

        placeholder="请输入名称"
      />
      <ProForm.Group size={10} spaceProps={{size: 10}}   grid={true} labelLayout={"inline"}>
        <ProFormText
          width="sm"
          name="name"
          label="汉语名称"

          placeholder="请输入名称"
        />

        <ProFormText
          width="sm"
          name="nameUg"
          label="维语名称"
          placeholder="请输入名称"
        />

        <ProFormMoney
          width="sm"
          name="paymentAmount"
          label="支付金额"
          disabled={true}

          placeholder="请输入名称"
        />

        <ProFormMoney
          width="sm"
          name="discountAmount"
          label="优惠金额"
          placeholder="请输入名称"
          disabled={true}
        />
        <ProFormMoney
          width="sm"
          name="totalAmount"
          label="总额"
          placeholder="请输入名称"
          disabled={true}
        />
        <ProFormText
          width="sm"
          name="quantity"
          label="总数"
          placeholder="0"
          disabled={true}
        />


        <ProFormSelect label="代理类型"  name="relationAgentId"     width="sm" debounceTime={300} request={async () => {
          return await findByAgentBySelectList ();
        }}/>
        <ProFormSelect label="升级代理" name="agentId"       width="sm" debounceTime={300} onChange={(e: number) => {
          console.log ( e )
          //fetchByList({taocanId:1,agentId:e})
          setAgent ( e )
        }} request={async () => {
          return await findByAgentBySelectList ();
        }}/>

      </ProForm.Group>
      <ProForm.Group>
        <ProFormItem
          name="imageId"
          label="图片"
        >
          <MyUpload
            type={1}
            onChange={(event) => {
              //  console.log(event?.id)
              // @ts-ignore
              //  setImageId ( event );
              // @ts-ignore
              formRef.current?.setFieldValue ( "imageId",event);
            }}
          ></MyUpload>
        </ProFormItem>
        <ProFormTextArea
          width="md"
          name="remark"
          label="备注"
          placeholder="请输入备注"

        />
      </ProForm.Group>
      <ProFormList
        name="goods"
        copyIconProps={false}
deleteIconProps={false} creatorButtonProps={false}      >
        {(f, index, action) => {
          console.log ( f )
          let currentRowData = action.getCurrentRowData ();
          let total = (currentRowData.price * currentRowData.quantity)
          console.log ( currentRowData, total )
          /*     action.setCurrentRowData({
                  paymentAmount: (currentRowData.price*currentRowData.quantity)
                //  remark: undefined,
                });*/
          return (<ProForm.Group grid={true} labelLayout={"inline"}>
              <ProFormText
                width="sm"
                name="name"
                label="商品名称"
                disabled={true}

                placeholder="请输入名称"
              />

              <ProFormMoney
                disabled={true}
                width="sm"
                name="price"
                label="价格"
                placeholder="请输入名称"
              />
              <ProFormMoney
                disabled={true}
                width="sm"
                name="paymentAmount"

                label="总价格"

                placeholder="请输入名称"
              />

              <ProFormDigit
                width="sm"
                name="quantity"
                label="个数"
                placeholder="请输入名称"
              />
            </ProForm.Group>
          );
        }}
      </ProFormList>
    </ModalForm>

  )
}

export default EditDialog;
